package com.zsl.blog.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.zsl.blog.api.dao.pojo.SysUser;
import com.zsl.blog.api.service.LoginService;
import com.zsl.blog.api.service.SysUserService;
import com.zsl.blog.api.utils.ErrorCode;
import com.zsl.blog.api.utils.JWTUtils;
import com.zsl.blog.api.vo.Result;
import com.zsl.blog.api.vo.params.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    private static final String SLAT = "zzssll*";
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result login(LoginParam param) {
        String userName = param.getAccount();
        String password = DigestUtils.md5Hex(param.getPassword()+SLAT);
        System.out.println(password);
        SysUser sysUser = sysUserService.findUser(userName,password);

        if (sysUser == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public SysUser checkToken(String token) {
        if(StringUtils.isEmpty(token)){
            return null;
        }
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null) {
            return null;
        }
        String userJson = (String) redisTemplate.opsForValue().get("TOKEN_"+token);
        if (userJson == null) {
            return null;
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return Result.success(null);
    }
}
